'use strict'
let route = require('./route')
let EventEmitter = require('events').EventEmitter
let userServerConfig = require('../config').userServerConfig
let util = require('util')
let rc4a = require('./rc4a.js')
  //角色服务器会话类(连接类)
class NodeSession {
  constructor(sId, socket) {
    this.id = sId
    this.serverId = null
    this.socket = socket
    let self = this
    socket.on('message', function(data) {
      Log(data)
      try {
        if (!Buffer.isBuffer(data) || data.length <= 4) {
          return
        }
        data = rc4a.decodeBuffer(data)
        data = JSON.parse(data)
        if (!util.isObject(data.msg)) {
          data.msg = {}
        }
      } catch (e) {
        return
      }
      Log(data)
      let method
      if (self.serverId) {
        method = route.getLogin(data.route)
        if (method) {
          method(self, data.msg, function(result) {
            Log(result)
            if (util.isNumber(result)) {
              result = {
                error: result
              }
            }
            self.send(result, data.reqId)
          })
        }
      } else {
        method = route.getNotLogin(data.route)
        if (method) {
          method(self, data.msg, function(result) {
            if (typeof result === 'number') {
              result = {
                error: result
              }
            }
            self.send(result, data.reqId)
          })
        }
      }

    })
    socket.on('close', function(data) {
      if (self.serverId) {
        Log(`节点服务器${self.serverId}关闭连接`)
        nodeSessionMgr.delSessionBySid(self.id)
      }
    })
    socket.on('error', function(data) {
      this.emit('close')
    })
  }

  //发送消息
  send(msg, reqId) {
    var sendData = {}
    if (reqId) {
      sendData['reqId'] = reqId
    }
    sendData['msg'] = msg
    Log(sendData)
    sendData = JSON.stringify(sendData)
    this.socket.send(rc4a.encodeStr(sendData))
  }

  //发送消息
  push(msg, route) {
    var sendData = {
      msg: msg,
      route: route
    }
    sendData = JSON.stringify(sendData)
    this.socket.send(sendData)
  }

  close() {
    this.socket.close()
  }
}


//会话管理类(用户连接管理类)
class NodeSessionMgr {
  constructor() {
    this.sessions = {} //保存socket.id对应的session
    this.sessionsSid = {} //保存角色服务器id对应的session
  }

  create(sId, socket) {
    socket.sId = sId
    var session = new NodeSession(sId, socket)
    this.sessions[sId] = session
    return session
  }

  get(sId) {
    return this.sessions[sId]
  }

  getByServerId(serverId) {
    return this.sessionsSid[serverId]
  }

  bind(sId, serverId) {
    if (this.sessionsSid[serverId]) {
      //不允许同一账号登陆多个客户端
      //服务器先断开原来的客户端
      this.sessionsSid[serverId].socket.close()
      this.delSession(this.sessionsSid[serverId])
    }
    Log(`节点服务器${serverId}连接`)
    let session = this.sessions[sId]
    session.serverId = serverId
    this.sessionsSid[serverId] = session
    return session
  }

  delSession(session) {
    delete this.sessions[session.sId]
    delete this.sessionsSid[session.serverId]
  }

  delSessionBySid(sId) {
    let session = this.sessions[sId]
    delete this.sessions[sId]
    delete this.sessionsSid[session.serverId]
  }

}

let nodeSessionMgr = new NodeSessionMgr()
module.exports = nodeSessionMgr
